<template>
  <div style="border: 1px solid #ccc;">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editor"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden;"
      v-model="html"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onCreated"
      @onChange="onChange"
    />
  </div>
</template>
<!--        @onCreated="handleCreated"-->
<!--&lt;!&ndash;        @onChange="handleChange"&ndash;&gt;-->
<!--&lt;!&ndash;        @onDestroyed="handleDestroyed"&ndash;&gt;-->
<!--&lt;!&ndash;        @onFocus="handleFocus"&ndash;&gt;-->
<!--&lt;!&ndash;        @onBlur="handleBlur"&ndash;&gt;-->
<!--&lt;!&ndash;        @customAlert="customAlert"&ndash;&gt;-->
<style src="@wangeditor/editor/dist/css/style.css"></style>
<script>
import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'


export default {
  name:'WebEditor',
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      html: '',
      toolbarConfig: { excludeKeys: [
          'uploadVideo'
        ]
      },
      editorConfig: { placeholder: '请输入内容...' ,
        MENU_CONF: {
          uploadImage: {
            server: process.env.VUE_APP_BASE_API + "/file/upload",
            fieldName: 'file',
            maxFileSize: 50 * 1024 * 1024,

            customInsert(res, insertFn) {                  // JS 语法
              // res 即服务端的返回结果
              // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
              // 先关闭等待的Message
              // 从 res 中找到 url alt href ，然后插入图片
              insertFn(res.data.url, null, null)
            },
            timeout: 30 * 1000,
          }
        }
      },
      mode: 'default', // or 'simple'
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  watch: {
    value(val) {
      if(val==null)
      {
        this.html='';
      }

      if (val && val !== this.html) {
        this.$nextTick(() => {
          if (this.editor) {
            this.html = val || '';
          }
        });
      }
    },
  },

  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor);
      this.html = this.value || '<p><br/></p>'; //
      // this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      // this.$nextTick(() => {
      //   if (this.html !== this.value) {
      //     this.html = this.value === null ? "" : this.value;
      //   }
      // })
      this.$emit('input',this.html);},
    onChange(editor) {
      this.$emit('input',this.html);
    },
  },
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    // setTimeout(() => {
    //   this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
    // }, 1500)
  },

  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
}
</script>

